<template>
  <div class="dialog-management">
    <el-card class="full-height-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon">
              <ChatDotRound />
            </el-icon>
            <span class="header-title">AI助手管理</span>
            <el-tag type="info" size="small">{{ pagination.total }} 个助手</el-tag>
          </div>
          <div class="header-actions">
            <el-button type="primary" @click="showCreateDialog" :icon="Plus">
              创建AI助手
            </el-button>
            <el-button @click="refreshData" :icon="Refresh" :loading="loading">
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :model="searchParams" inline class="search-form">
          <el-form-item label="场景筛选">
            <el-select v-model="searchParams.scene_id" placeholder="选择场景" clearable filterable style="width: 200px">
              <el-option v-for="scene in sceneOptions" :key="scene.value" :label="scene.displayLabel || scene.label"
                :value="scene.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="交互模式">
            <el-select v-model="searchParams.interactive_mode" placeholder="选择交互模式" clearable style="width: 150px">
              <el-option label="对话框" :value="1">
                <el-icon>
                  <ChatDotRound />
                </el-icon>
                <span style="margin-left: 8px">对话框</span>
              </el-option>
              <el-option label="语音通话" :value="2">
                <el-icon>
                  <Phone />
                </el-icon>
                <span style="margin-left: 8px">语音通话</span>
              </el-option>
              <el-option label="视频聊天" :value="3">
                <el-icon>
                  <VideoCamera />
                </el-icon>
                <span style="margin-left: 8px">视频聊天</span>
              </el-option>
            </el-select>
          </el-form-item>


          <el-form-item>
            <el-button type="primary" @click="loadDialogs" :icon="Search" :loading="loading">
              搜索
            </el-button>
            <el-button @click="resetSearch" :icon="Refresh">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <div class="table-container">
        <el-table :data="dialogList" v-loading="loading" :height="tableHeight" stripe border empty-text="暂无AI助手配置"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" sortable />

          <el-table-column label="场景信息" min-width="200">
            <template #default="scope">
              <div class="scene-info">
                <div class="scene-name">{{ getSceneName(scope.row.scene_id) }}</div>
                <div class="scene-id">ID: {{ scope.row.scene_id }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="助手配置" min-width="180">
            <template #default="scope">
              <div class="dialog-config">
                <div class="config-item">
                  <el-icon>
                    <Monitor />
                  </el-icon>
                  <span>{{ scope.row.dialog_size.width }}×{{ scope.row.dialog_size.height }}</span>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="交互模式" min-width="120">
            <template #default="scope">
              <el-tag :type="getInteractiveModeType(scope.row.interactive_mode)"
                :icon="getInteractiveModeIcon(scope.row.interactive_mode)">
                {{ getInteractiveModeText(scope.row.interactive_mode) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="关联智能体" min-width="150">
            <template #default="scope">
              <div class="agent-info">
                <div v-if="scope.row.agent_ids">
                  <el-tag v-for="agentId in scope.row.agent_ids.split(',').slice(0, 2)" :key="agentId" size="small"
                    type="primary" style="margin-right: 4px; margin-bottom: 2px">
                    {{ getAgentDisplayName(agentId.trim()) }}
                  </el-tag>
                  <el-tag v-if="scope.row.agent_ids.split(',').length > 2" size="small" type="info"
                    style="margin-right: 4px">
                    +{{ scope.row.agent_ids.split(',').length - 2 }}
                  </el-tag>
                </div>
                <el-text v-else type="info" size="small">未关联</el-text>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="按钮配置" min-width="120">
            <template #default="scope">
              <div class="buttons-info">
                <el-tag v-if="scope.row.buttons.length > 0" size="small">
                  {{ scope.row.buttons.length }} 个按钮
                </el-tag>
                <el-tag v-else type="info" size="small">无按钮</el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="created_time" label="创建时间" min-width="160" sortable>
            <template #default="scope">
              {{ formatDateTime(scope.row.created_time) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="280" fixed="right">
            <template #default="scope">
              <div class="action-buttons">
                <el-button size="small" type="success" @click="handleStartAgent(scope.row)"
                  :icon="getInteractiveModeIcon(scope.row.interactive_mode)">
                  启动助手
                </el-button>
                <el-button size="small" type="primary" @click="editDialog(scope.row)" :icon="Edit">
                  编辑
                </el-button>
                <el-popconfirm title="确定要删除这个AI助手吗？" @confirm="deleteDialog(scope.row)">
                  <template #reference>
                    <el-button size="small" type="danger" :icon="Delete">
                      删除
                    </el-button>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 批量操作栏 -->
        <div v-if="selectedDialogs.length > 0" class="batch-actions">
          <div class="batch-info">
            已选择 {{ selectedDialogs.length }} 个助手
          </div>
          <div class="batch-buttons">
            <el-button type="danger" @click="batchDelete" :icon="Delete">
              批量删除
            </el-button>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.page_size"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadDialogs" @current-change="loadDialogs" />
      </div>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="isEdit ? '编辑AI助手' : '创建AI助手'" width="800px" @close="resetForm"
      :close-on-click-modal="false" class="dialog-form">
      <el-form :model="dialogForm" :rules="dialogRules" ref="dialogFormRef" label-width="120px" class="compact-form">
        <!-- 基础信息 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关联场景" prop="scene_id">
              <el-select v-model="dialogForm.scene_id" placeholder="选择场景" filterable :disabled="isEdit"
                style="width: 100%" @change="onSceneChange">
                <el-option v-for="scene in sceneOptions" :key="scene.value" :label="scene.displayLabel || scene.label"
                  :value="scene.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="交互模式" prop="interactive_mode">
              <el-select v-model="dialogForm.interactive_mode" placeholder="选择交互模式" style="width: 100%">
                <el-option label="对话框" :value="1">
                  <div class="mode-option">
                    <el-icon>
                      <ChatDotRound />
                    </el-icon>
                    <span>对话框</span>
                  </div>
                </el-option>
                <el-option label="语音通话" :value="2">
                  <div class="mode-option">
                    <el-icon>
                      <Phone />
                    </el-icon>
                    <span>语音通话</span>
                  </div>
                </el-option>
                <el-option label="视频聊天" :value="3">
                  <div class="mode-option">
                    <el-icon>
                      <VideoCamera />
                    </el-icon>
                    <span>视频聊天</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 智能体选择 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="关联智能体">
              <el-select v-model="selectedAgentIds" placeholder="选择要关联的智能体" multiple filterable style="width: 100%"
                :loading="agentOptionsLoading" @change="onAgentSelectionChange">
                <el-option v-for="agent in agentOptions" :key="agent.agent_id"
                  :label="`${agent.agent_name} (${agent.agent_id.slice(0, 8)}...)`" :value="agent.agent_id">
                  <div class="agent-option">
                    <span class="agent-name">{{ agent.agent_name }}</span>
                    <el-tag :type="agent.status === '1' ? 'success' : agent.status === '2' ? 'warning' : 'info'"
                      size="small" style="margin-left: 8px">
                      {{ getAgentStatusText(agent.status) }}
                    </el-tag>
                  </div>
                </el-option>
              </el-select>
              <div class="agent-hint">
                <el-text type="info" size="small">
                  可选择多个智能体，助手将使用第一个启用状态的智能体
                </el-text>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 窗口设置 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="窗口宽度">
              <el-input-number v-model="dialogForm.dialog_size.width" :min="200" :max="1920" :step="50"
                style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="窗口高度">
              <el-input-number v-model="dialogForm.dialog_size.height" :min="150" :max="1080" :step="50"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="快速设置">
              <div class="size-presets-compact">
                <el-button size="small" @click="setSizePreset(400, 600)"
                  :type="isCurrentSize(400, 600) ? 'primary' : 'default'">
                  小窗口 (400×600)
                </el-button>
                <el-button size="small" @click="setSizePreset(800, 600)"
                  :type="isCurrentSize(800, 600) ? 'primary' : 'default'">
                  中窗口 (800×600)
                </el-button>
                <el-button size="small" @click="setSizePreset(1200, 800)"
                  :type="isCurrentSize(1200, 800) ? 'primary' : 'default'">
                  大窗口 (1200×800)
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 按钮配置 -->
        <el-form-item label="自定义按钮">
          <div class="buttons-config-compact">
            <div class="buttons-header-compact">
              <span>按钮配置 ({{ dialogForm.buttons.length }})</span>
              <el-button type="primary" size="small" @click="addButton" :icon="Plus">
                添加按钮
              </el-button>
            </div>

            <div v-if="dialogForm.buttons.length === 0" class="empty-buttons-compact">
              <el-text type="info">暂无自定义按钮</el-text>
            </div>

            <div v-else class="button-list-compact">
              <div v-for="(button, index) in dialogForm.buttons" :key="index" class="button-item-compact">
                <el-row :gutter="12" align="middle">
                  <el-col :span="5">
                    <el-input v-model="button.id" placeholder="按钮ID" size="small" />
                  </el-col>
                  <el-col :span="5">
                    <el-input v-model="button.text" placeholder="按钮文本" size="small" />
                  </el-col>
                  <el-col :span="4">
                    <el-select v-model="button.type" placeholder="类型" size="small" style="width: 100%">
                      <el-option label="主要" value="primary" />
                      <el-option label="成功" value="success" />
                      <el-option label="警告" value="warning" />
                      <el-option label="危险" value="danger" />
                      <el-option label="信息" value="info" />
                    </el-select>
                  </el-col>
                  <el-col :span="5">
                    <el-input v-model="button.action" placeholder="动作" size="small" />
                  </el-col>
                  <el-col :span="3">
                    <el-button :type="button.type" size="small" disabled>
                      {{ button.text || '预览' }}
                    </el-button>
                  </el-col>
                  <el-col :span="2">
                    <el-button type="danger" size="small" @click="removeButton(index)" :icon="Delete" circle />
                  </el-col>
                </el-row>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="saveDialog" :loading="submitLoading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, ChatDotRound, Phone, VideoCamera, Edit, Delete, Monitor, View, Setting, Operation, Cellphone, FullScreen, Close, Check } from '@element-plus/icons-vue'
import { sceneApi, dialogApi } from '@/api/scene'
import { agentApi } from '@/api/agent'
import { WindowManager } from '@/utils/windowManager'

// 类型定义
interface SceneOption {
  value: string
  label: string
  level: number
  status: string
  description?: string
  displayLabel?: string
}

interface AgentOption {
  agent_id: string
  agent_name: string
  status: string
  scene_id: string
}

interface DialogSize {
  width: number
  height: number
}

interface ButtonConfig {
  id: string
  text: string
  type: string
  action: string
}

interface DialogItem {
  id: number
  scene_id: string
  agent_ids?: string
  dialog_size: DialogSize
  interactive_mode: number
  buttons: ButtonConfig[]
  created_time: string
  updated_time?: string
}

interface SearchParams {
  scene_id: string
  interactive_mode: number | null
}

interface DialogForm {
  id?: number
  scene_id: string
  agent_ids?: string
  dialog_size: DialogSize
  interactive_mode: number
  buttons: ButtonConfig[]
}

// 响应式数据
const loading = ref(false)
const dialogList = ref<DialogItem[]>([])
const sceneOptions = ref<SceneOption[]>([])
const agentOptions = ref<AgentOption[]>([])
const agentOptionsLoading = ref(false)
const selectedAgentIds = ref<string[]>([])
const dialogFormVisible = ref(false)
const isEdit = ref(false)
const selectedDialogs = ref<number[]>([])
const submitLoading = ref(false)

// 全局智能体映射，用于在表格中显示智能体名称
const allAgentsMap = ref<Map<string, AgentOption>>(new Map())

// 聊天对话框相关
const currentChatConfig = ref<DialogItem | null>(null)

// 计算表格高度
const tableHeight = computed(() => {
  return window.innerHeight - 280
})

// 搜索参数
const searchParams = reactive<SearchParams>({
  scene_id: '',
  interactive_mode: null
})

// 分页参数
const pagination = reactive({
  page: 1,
  page_size: 20,
  total: 0
})

// 对话框表单
const dialogForm = reactive<DialogForm>({
  scene_id: '',
  agent_ids: '',
  dialog_size: {
    width: 400,
    height: 300
  },
  interactive_mode: 1,
  buttons: []
})

// 表单验证规则
const dialogRules = {
  scene_id: [{ required: true, message: '请选择场景', trigger: 'change' }],
  interactive_mode: [{ required: true, message: '请选择交互模式', trigger: 'change' }]
}

const dialogFormRef = ref()

// 方法
const loadSceneOptions = async () => {
  try {
    const response = await sceneApi.getSceneOptions()
    sceneOptions.value = response.map((scene: any) => ({
      ...scene,
      displayLabel: `${'　'.repeat(scene.level)}${scene.label}${scene.level > 0 ? ` (L${scene.level})` : ''}`
    }))
  } catch (error) {
    ElMessage.error('加载场景选项失败')
  }
}

const loadDialogs = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      page_size: pagination.page_size,
      ...searchParams
    }

    Object.keys(params).forEach((key: string) => {
      if (params[key] === '' || params[key] === null) {
        delete params[key]
      }
    })

    const response = await dialogApi.getDialogs(params)
    dialogList.value = response.dialogs
    pagination.total = response.total_count
  } catch (error) {
    ElMessage.error('加载对话框列表失败')
  } finally {
    loading.value = false
  }
}

const getInteractiveModeText = (value: number): string => {
  switch (value) {
    case 1:
      return '对话框'
    case 2:
      return '语音通话'
    case 3:
      return '视频聊天'
    default:
      return '未知'
  }
}

const showCreateDialog = () => {
  isEdit.value = false
  dialogFormVisible.value = true
  resetForm()
}

const editDialog = (row: DialogItem) => {
  isEdit.value = true
  dialogFormVisible.value = true

  Object.assign(dialogForm, {
    id: row.id,
    scene_id: row.scene_id,
    agent_ids: row.agent_ids || '',
    dialog_size: { ...row.dialog_size },
    interactive_mode: row.interactive_mode,
    buttons: [...row.buttons]
  })

  // 解析 agent_ids 字符串为数组
  if (row.agent_ids) {
    selectedAgentIds.value = row.agent_ids.split(',').filter(id => id.trim())
  } else {
    selectedAgentIds.value = []
  }

  // 加载对应场景的智能体选项
  loadAgentOptions(row.scene_id)
}

const deleteDialog = async (row: DialogItem) => {
  try {
    await ElMessageBox.confirm('确定要删除这个对话框吗？', '确认删除', {
      type: 'warning'
    })

    await dialogApi.deleteDialog(row.id)
    ElMessage.success('删除成功')
    loadDialogs()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const saveDialog = async () => {
  try {
    await dialogFormRef.value.validate()

    if (isEdit.value) {
      await dialogApi.updateDialog(dialogForm.id!, dialogForm)
      ElMessage.success('更新成功')
    } else {
      await dialogApi.createDialog(dialogForm)
      ElMessage.success('创建成功')
    }

    dialogFormVisible.value = false
    loadDialogs()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  }
}

const addButton = () => {
  dialogForm.buttons.push({
    id: `btn_${Date.now()}`,
    text: '新按钮',
    type: 'primary',
    action: 'custom'
  })
}

const removeButton = (index: number) => {
  dialogForm.buttons.splice(index, 1)
}

const resetForm = () => {
  Object.assign(dialogForm, {
    scene_id: '',
    agent_ids: '',
    dialog_size: {
      width: 400,
      height: 300
    },
    interactive_mode: 1,
    buttons: []
  })

  // 重置智能体选择
  selectedAgentIds.value = []
  agentOptions.value = []
}

const resetSearch = () => {
  Object.assign(searchParams, {
    scene_id: '',
    interactive_mode: null
  })
  pagination.page = 1
  loadDialogs()
}

const openPopupWindow = async (row: DialogItem) => {
  try {
    switch (row.interactive_mode) {
      case 1:
        await WindowManager.createChatWindow(row)
        break
      case 2:
        await WindowManager.createVoiceCallWindow(row)
        break
      case 3:
        await WindowManager.createVideoCallWindow(row)
        break
    }
    ElMessage.success('弹出窗口已创建')
  } catch (error) {
    ElMessage.error('创建弹出窗口失败，请检查浏览器弹窗设置')
    console.error('创建弹出窗口失败:', error)
  }
}

const closeChatDialog = () => {
  currentChatConfig.value = null
}

// 生命周期
onMounted(() => {
  loadSceneOptions()
  loadAllAgents()
  loadDialogs()
})

// 获取场景名称
const getSceneName = (sceneId: string): string => {
  const scene = sceneOptions.value.find(s => s.value === sceneId)
  return scene ? scene.label : sceneId
}

const getInteractiveModeType = (value: number): string => {
  switch (value) {
    case 1:
      return 'info'
    case 2:
      return 'success'
    case 3:
      return 'warning'
    default:
      return 'info'
  }
}

const getInteractiveModeIcon = (value: number) => {
  switch (value) {
    case 1:
      return ChatDotRound
    case 2:
      return Phone
    case 3:
      return VideoCamera
    default:
      return ChatDotRound
  }
}

const handleSelectionChange = (selected: DialogItem[]) => {
  selectedDialogs.value = selected.map(d => d.id)
}

const batchDelete = async () => {
  try {
    await ElMessageBox.confirm('确定要批量删除这些AI助手吗？', '确认批量删除', {
      type: 'warning'
    })

    // 逐个删除选中的对话框
    for (const id of selectedDialogs.value) {
      await dialogApi.deleteDialog(id)
    }

    ElMessage.success('批量删除成功')
    selectedDialogs.value = []
    loadDialogs()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

const formatDateTime = (timestamp: string): string => {
  const date = new Date(timestamp)
  return date.toLocaleString()
}

const setSizePreset = (width: number, height: number) => {
  dialogForm.dialog_size.width = width
  dialogForm.dialog_size.height = height
}

const isCurrentSize = (width: number, height: number) => {
  return dialogForm.dialog_size.width === width && dialogForm.dialog_size.height === height
}

const refreshData = () => {
  resetSearch()
}

const handleStartAgent = async (row: DialogItem) => {
  try {
    let agent: any = null

    // 如果对话框配置了关联的智能体，优先使用配置的智能体
    if (row.agent_ids) {
      const agentIds = row.agent_ids.split(',').map(id => id.trim()).filter(id => id)

      if (agentIds.length > 0) {
        ElMessage.info('正在使用配置的智能体...')

        // 尝试获取第一个配置的智能体
        for (const agentId of agentIds) {
          try {
            agent = await agentApi.getAgentById(agentId)
            if (agent && agent.status === 1) {
              break // 找到启用状态的智能体
            }
          } catch (error) {
            console.warn(`智能体 ${agentId} 不存在或无法访问`)
          }
        }

        if (!agent || agent.status !== 1) {
          ElMessage.warning('配置的智能体都不可用，正在查找场景下的其他智能体...')
        }
      }
    }

    // 如果没有配置智能体或配置的智能体不可用，则根据场景查找
    if (!agent || agent.status !== 1) {
      ElMessage.info('正在查找智能体配置...')
      const agentsResponse = await agentApi.getAgentsByScene(row.scene_id, { status: '1' })

      if (!agentsResponse.items || agentsResponse.items.length === 0) {
        ElMessage.warning('该场景下没有可用的智能体，请先创建智能体配置')
        return
      }

      agent = agentsResponse.items[0]
    }

    console.log('获取到的智能体数据:', agent)

    ElMessage.info(`正在启动助手 "${agent.agent_name}"...`)
    const response = await agentApi.startAgent(agent)
    ElMessage.success(`助手 "${agent.agent_name}" 启动成功！正在打开聊天窗口...`)
    console.log('启动助手成功:', response)

    // 启动成功后，打开弹出窗口
    await openPopupWindow(row)
  } catch (error: any) {
    console.error('启动助手失败:', error)
    const errorMsg = error.response?.data?.detail || error.message || '启动助手失败'
    ElMessage.error(`启动助手失败: ${errorMsg}`)
  }
}

const onSceneChange = (sceneId: string) => {
  // 清空已选择的智能体
  selectedAgentIds.value = []
  dialogForm.agent_ids = ''
  // 加载新场景下的智能体
  loadAgentOptions(sceneId)
}

const onAgentSelectionChange = (agentIds: string[]) => {
  // 将选择的智能体ID数组转换为逗号分隔的字符串
  dialogForm.agent_ids = agentIds.join(',')
}

const getAgentStatusText = (status: string): string => {
  switch (status) {
    case '0':
      return '停用'
    case '1':
      return '启用'
    case '2':
      return '训练中'
    default:
      return '未知'
  }
}

const getAgentDisplayName = (agentId: string): string => {

  // 首先从全局智能体映射中查找
  const agent = allAgentsMap.value.get(agentId)
  if (agent) {
    return agent.agent_name
  }

  // 如果全局映射中没有，再从当前场景的智能体选项中查找
  const agentOption = agentOptions.value.find(a => a.agent_id === agentId)
  if (agentOption) {
    return agentOption.agent_name
  }

  // 如果都找不到，则显示ID
  console.log('未找到智能体名称，显示ID')
  return agentId.length > 12 ? agentId.slice(0, 8) + '...' : agentId
}

// 智能体相关方法
const loadAgentOptions = async (sceneId?: string) => {
  if (!sceneId) {
    agentOptions.value = []
    return
  }

  agentOptionsLoading.value = true
  try {
    const response = await agentApi.getAgentsByScene(sceneId, { status: '1' })
    agentOptions.value = response.items.map((agent: any) => ({
      agent_id: agent.agent_id,
      agent_name: agent.agent_name,
      status: agent.status,
      scene_id: agent.scene_id
    }))
    console.log('当前场景智能体选项:', agentOptions.value)
  } catch (error) {
    console.error('加载智能体选项失败:', error)
    ElMessage.error('加载智能体选项失败')
    agentOptions.value = []
  } finally {
    agentOptionsLoading.value = false
  }
}

// 加载所有智能体信息，用于构建全局映射
const loadAllAgents = async () => {
  try {
    const agentsMap = new Map<string, AgentOption>()
    let page = 1
    const pageSize = 100 // 使用最大允许的页面大小
    let hasMore = true

    // 循环获取所有页面的数据
    while (hasMore) {
      const response = await agentApi.getAgents({
        page: page,
        page_size: pageSize
      })

      // 添加当前页的智能体到映射中
      response.items.forEach((agent: any) => {
        agentsMap.set(agent.agent_id, {
          agent_id: agent.agent_id,
          agent_name: agent.agent_name,
          status: agent.status,
          scene_id: agent.scene_id
        })
      })

      // 检查是否还有更多数据
      hasMore = response.items.length === pageSize
      page++
    }

    allAgentsMap.value = agentsMap
    console.log('全局智能体映射:', Array.from(allAgentsMap.value.entries()))
  } catch (error) {
    console.error('加载所有智能体失败:', error)
  }
}
</script>

<style scoped>
.dialog-management {
  height: 100vh;
  padding: 20px;
  box-sizing: border-box;
}

.full-height-card {
  height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
}

.full-height-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 20px;
  color: #409eff;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 8px;
  flex-shrink: 0;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: end;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.table-container {
  flex: 1;
  margin-bottom: 20px;
  position: relative;
}

.scene-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.scene-name {
  font-weight: 500;
  color: #303133;
}

.scene-id {
  font-size: 12px;
  color: #909399;
}

.dialog-config {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.config-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #606266;
}

.config-item .el-icon {
  font-size: 14px;
  color: #909399;
}

.buttons-info {
  display: flex;
  justify-content: center;
}

.agent-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.agent-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.agent-name {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.agent-hint {
  margin-top: 4px;
  padding-left: 12px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.action-buttons .el-button {
  margin: 0;
}

.batch-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 6px;
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 10;
}

.batch-info {
  color: #1e40af;
  font-weight: 500;
}

.batch-buttons {
  display: flex;
  gap: 8px;
}

.pagination-section {
  text-align: center;
  flex-shrink: 0;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.input-hint {
  font-size: 12px;
  color: #909399;
  text-align: center;
  margin-top: 4px;
}

.size-presets-compact {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  justify-content: flex-start;
}

.size-presets-compact .el-button {
  min-width: 140px;
  padding: 8px 16px;
}

.buttons-config-compact {
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  padding: 16px;
  background: #fafafa;
}

.buttons-header-compact {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-weight: 500;
  color: #303133;
}

.empty-buttons-compact {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.button-list-compact {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.button-item-compact {
  padding: 12px;
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  transition: all 0.3s;
}

.button-item-compact:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.dialog-footer {
  text-align: right;
  padding: 16px 0 0 0;
  border-top: 1px solid #ebeef5;
}

.dialog-footer .el-button {
  margin-left: 12px;
}

/* 基础样式 */
:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table .el-table__cell) {
  padding: 12px 0;
}

:deep(.el-table .el-button) {
  margin: 0 2px;
}

:deep(.el-tag) {
  font-weight: 500;
}

/* 动画效果 */
.el-table__row {
  transition: all 0.3s;
}

.el-table__row:hover {
  transform: translateY(-1px);
}

.search-section {
  animation: slideInDown 0.5s ease-out;
}

@keyframes slideInDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.table-container {
  animation: fadeInUp 0.6s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .search-form .el-form-item {
    width: 100%;
  }

  .action-buttons {
    flex-direction: column;
  }
}

@media (max-width: 768px) {
  .dialog-management {
    padding: 10px;
  }

  .full-height-card {
    height: calc(100vh - 20px);
  }

  .search-section {
    padding: 15px;
  }

  .header-left {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .header-actions {
    flex-direction: column;
    gap: 8px;
  }

  .batch-actions {
    flex-direction: column;
    gap: 8px;
    text-align: center;
  }
}
</style>